<?php
/**
 *
 */
class ClassFactory
{
	private static $singletonObject = array();
	
	public static function forName()
	{
		$args = func_get_args();
		$argsNum = func_num_args();
		if(!$argsNum) throw new Exception('ClassFactory::forName exception, path empty');
		$path = trim($args[0]);

		$keys = array_keys(self::$singletonObject);
		if(in_array($path, $keys)) return self::$singletonObject[$path];

		import($path);
		$className = end(explode('.', $path));
		if($argsNum > 1)
		{
			$argString = '';
			for($i = 1; $i < $argsNum; $i++)
			{
				$argString .= $argString ? ',' . '$args[' . $i . ']' : '$args[' . $i . ']';
			}
			$classString = $className . "($argString);";
			
			if(!class_exists($className)) throw new Exception('class ' . $classString . ' not exist');
			return self::$singletonObject[$path] = eval('return new ' . $classString);
		}
		
		if(!class_exists($className)) throw new Exception('class ' . $className . ' not exist');
		return self::$singletonObject[$path] = new $className();
	}
	
	public static function getSingleton()
	{
		$args = func_get_args();
		$argsNum = func_num_args();
		if(!$argsNum) throw new DuDuLookException('ClassFactory::getSingleton exception, path empty');
		$path = trim($args[0]);

		$keys = array_keys(self::$singletonObject);
		if(in_array($path, $keys)) return self::$singletonObject[$path];

		import($path);
		$className = end(explode('.', $path));
		if($argsNum > 1)
		{
			$argString = '';
			for($i = 1; $i < $argsNum; $i++)
			{
				$argString .= $argString ? ',' . '$args[' . $i . ']' : '$args[' . $i . ']';
			}
			$classString = $className . "($argString);";
			return self::$singletonObject[$path] = eval('return new ' . $classString);
		}

		return self::$singletonObject[$path] = new $className();
	}

	public static function toString()
	{
		print_r(self::$singletonObject);
	}
}
?>